package com.neusoft.databus.policy.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.databus.policy.enums.EventStatus;
import com.neusoft.databus.policy.enums.PolicyType;
import com.neusoft.databus.policy.model.Event;
import com.neusoft.databus.policy.model.QEvent;
import com.neusoft.databus.policy.repository.CustomizedEventRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedEventRepositoryImpl extends AbstractRepository implements CustomizedEventRepository {

    @Override
    public Page<Event> search(final Pageable pageable, final Searchable searchable) {
        final QEvent qEvent = QEvent.event;
        final BooleanBuilder where = new BooleanBuilder();
        where.and(super.equalsLong(qEvent.policy.id, searchable, "policyId"));
        where.and(super.inStrings(qEvent.code, searchable, "code"));
        where.and(super.containsStr(qEvent.resourceCode, searchable, "resourceCode"));
        where.and(super.containsStr(qEvent.policy.code, searchable, "policyCode"));
        where.and(super.containsStr(qEvent.policy.name, searchable, "policyName"));
        where.and(super.containsStr(qEvent.metricCode, searchable, "metricCode"));
        where.and(super.equalsEnum(qEvent.policy.policyType, searchable, "type", value -> PolicyType.valueOf(value)));
        where.and(super.equalsEnum(qEvent.status, searchable, "status", value -> EventStatus.valueOf(value)));
        final JPAQuery<Event> query = this.query().selectFrom(qEvent).where(where);
        return super.search(query, pageable);
    }

    @Override
    public List<Event> search(final Searchable searchable) {
        final QEvent qEvent = QEvent.event;
        final BooleanBuilder where = new BooleanBuilder();
        where.and(super.equalsLong(qEvent.policy.id, searchable, "policyId"));
        where.and(super.inStrings(qEvent.code, searchable, "code"));
        where.and(super.containsStr(qEvent.resourceCode, searchable, "resourceCode"));
        where.and(super.containsStr(qEvent.policy.code, searchable, "policyCode"));
        where.and(super.containsStr(qEvent.policy.name, searchable, "policyName"));
        where.and(super.containsStr(qEvent.metricCode, searchable, "metricCode"));
        where.and(super.equalsEnum(qEvent.policy.policyType, searchable, "type", value -> PolicyType.valueOf(value)));
        where.and(super.equalsEnum(qEvent.status, searchable, "status", value -> EventStatus.valueOf(value)));
        final JPAQuery<Event> query = this.query().selectFrom(qEvent).where(where);
        return query.fetch();
    }

    @Override
    protected Class<?> getModelClass() {
        return Event.class;
    }

}
